//
//  MoviePlayerExampleViewController.m
//  MoviePlayerExample
//

#import "MoviePlayerExampleViewController.h"

@implementation MoviePlayerExampleViewController

- (void)moviePlayerDidFinish:(NSNotification *)aNote {

	MPMoviePlayerController *player = [aNote object];
	[[NSNotificationCenter defaultCenter]
	 removeObserver:self
	 name:MPMoviePlayerPlaybackDidFinishNotification
	 object:player];

	[player stop];
	[activityView stopAnimating];
	
	[playerController.view removeFromSuperview];
	[playerController release];
}

- (void)loadStateChange:(NSNotification *)aNote {
	MPMoviePlayerController *player = [aNote object];
	
	if (player.loadState == MPMovieLoadStatePlayable || MPMovieLoadStatePlaythroughOK) {
		[activityView stopAnimating];
	}
	else {
		[activityView startAnimating];
	}
}

- (void)buttonClick:(id)sender {
	
	NSURL *movieURL = [NSURL
	URLWithString:@"http://images.apple.com/movies/us/hd_gallery/gl1800/480p/mammoth_480pr.mov"];
	
	playerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
	playerController.shouldAutoplay = NO;
	playerController.initialPlaybackTime = 5.0;
	playerController.controlStyle = MPMovieControlStyleEmbedded;
	
	playerController.backgroundView.backgroundColor = [UIColor yellowColor];
	
	CGRect playerFrame = CGRectInset(self.view.bounds, 50.0, 50.0);
	playerController.view.frame = playerFrame;
	[self.view addSubview:playerController.view];
	
	[[NSNotificationCenter defaultCenter]
	 addObserver:self
	 selector:@selector(moviePlayerDidFinish:)
	 name:MPMoviePlayerPlaybackDidFinishNotification
	 object:playerController];
	[[NSNotificationCenter defaultCenter]
	 addObserver:self
	 selector:@selector(loadStateChange:)
	 name:MPMoviePlayerLoadStateDidChangeNotification
	 object:playerController];
	
	[activityView startAnimating];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[btn setFrame:CGRectMake(100,110,120,34)];
	[btn setTitle:@"Show Movie" forState:UIControlStateNormal];
	[btn addTarget:self action:@selector(buttonClick:)
  forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btn];
	
	CGRect activityFrame = CGRectMake(130,10,40,40);
	activityView = [[UIActivityIndicatorView alloc]
					initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	[activityView setFrame:activityFrame];
	[self.view addSubview:activityView];
}

- (void)dealloc {
    [super dealloc];
}

@end
